package com.lw.lost.fragments

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.lw.lost.R
import com.lw.lost.adapters.RecommendUserAdapter
import com.lw.lost.databinding.FragmentHomeBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.RecommendUser
import com.lw.lost.utils.PreferenceUtils

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: DBlost
    private lateinit var recommendAdapter: RecommendUserAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        db = DBlost(requireContext())
        
        initViews()
        loadRecommendUsers()
    }

    private fun initViews() {
        // 初始化RecyclerView
        recommendAdapter = RecommendUserAdapter()
        binding.rvRecommendUsers.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = recommendAdapter
        }

        // 搜索框点击事件
        binding.searchCard.setOnClickListener {
            showSearchDialog()
        }

        // 智能匹配点击事件
        binding.cardSmartMatch.setOnClickListener {
            loadRecommendUsers()
            Toast.makeText(context, "已为您智能推荐", Toast.LENGTH_SHORT).show()
        }

        // 精准匹配点击事件
        binding.cardPreciseMatch.setOnClickListener {
            showPreciseMatchDialog()
        }
    }

    private fun loadRecommendUsers() {
        val currentUserId = PreferenceUtils.getUserId(requireContext())
        val cursor = db.userDao.getRecommendUsers(currentUserId)
        val users = mutableListOf<RecommendUser>()

        while (cursor.moveToNext()) {
            users.add(
                RecommendUser(
                    userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                    name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
                    info = "${if (cursor.getInt(cursor.getColumnIndexOrThrow("gender")) == 0) "男" else "女"} · " +
                            "${cursor.getInt(cursor.getColumnIndexOrThrow("age"))}岁 · " +
                            "${cursor.getString(cursor.getColumnIndexOrThrow("education"))}",
                    interests = cursor.getString(cursor.getColumnIndexOrThrow("interests")) ?: "",
                    avatar = cursor.getString(cursor.getColumnIndexOrThrow("avatar")),
                    matchRate = "85%" // 这里可以根据实际算法计算匹配度
                )
            )
        }
        cursor.close()

        recommendAdapter.submitList(users)
    }

    private fun showPreciseMatchDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_precise_match, null)
        
        // 初始化学历选择器
        val spinnerEducation = dialogView.findViewById<AutoCompleteTextView>(R.id.spinnerEducation)
        val educationOptions = arrayOf("小学", "初中", "高中", "中专", "大专", "本科", "硕士", "博士")
        val educationAdapter = ArrayAdapter(requireContext(), R.layout.item_dropdown_menu, educationOptions)
        spinnerEducation.setAdapter(educationAdapter)

        // 创建对话框
        val dialog = AlertDialog.Builder(requireContext())
            .setTitle("精准匹配")
            .setView(dialogView)
            .create()

        // 设置匹配按钮点击事件
        dialogView.findViewById<MaterialButton>(R.id.btnMatch).setOnClickListener {
            val education = spinnerEducation.text.toString()
            val gender = if (dialogView.findViewById<RadioButton>(R.id.rbMale).isChecked) 0 else 1
            val minAge = dialogView.findViewById<TextInputEditText>(R.id.etMinAge).text.toString()
            val maxAge = dialogView.findViewById<TextInputEditText>(R.id.etMaxAge).text.toString()
            val interests = dialogView.findViewById<TextInputEditText>(R.id.etInterests).text.toString()

            // 验证输入
            if (education.isEmpty() || minAge.isEmpty() || maxAge.isEmpty() || interests.isEmpty()) {
                Toast.makeText(context, "请填写完整信息", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 执行匹配
            val cursor = db.userDao.searchPreciseMatch(
                gender = gender,
                minAge = minAge.toInt(),
                maxAge = maxAge.toInt(),
                education = education,
                interests = interests
            )

            val users = mutableListOf<RecommendUser>()
            cursor.use { cursor ->
                while (cursor.moveToNext()) {
                    users.add(
                        RecommendUser(
                            userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                            name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
                            info = "${if (cursor.getInt(cursor.getColumnIndexOrThrow("gender")) == 0) "男" else "女"} · " +
                                    "${cursor.getInt(cursor.getColumnIndexOrThrow("age"))}岁 · " +
                                    "${cursor.getString(cursor.getColumnIndexOrThrow("education"))}",
                            interests = cursor.getString(cursor.getColumnIndexOrThrow("interests")) ?: "",
                            avatar = cursor.getString(cursor.getColumnIndexOrThrow("avatar")),
                            matchRate = "匹配"
                        )
                    )
                }
            }

            recommendAdapter.submitList(users)
            dialog.dismiss()
        }

        dialog.show()
    }

    private fun showSearchDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_search, null)
        val etKeyword = dialogView.findViewById<TextInputEditText>(R.id.etKeyword)

        val dialog = AlertDialog.Builder(requireContext())
            .setTitle("搜索")
            .setView(dialogView)
            .create()

        dialogView.findViewById<MaterialButton>(R.id.btnSearch).setOnClickListener {
            val keyword = etKeyword.text.toString().trim()
            if (keyword.isEmpty()) {
                Toast.makeText(context, "请输入搜索关键词", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 执行搜索
            val cursor = db.userDao.searchUsers(keyword)
            val users = mutableListOf<RecommendUser>()

            cursor.use { cursor ->
                while (cursor.moveToNext()) {
                    users.add(
                        RecommendUser(
                            userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                            name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
                            info = "${if (cursor.getInt(cursor.getColumnIndexOrThrow("gender")) == 0) "男" else "女"} · " +
                                    "${cursor.getInt(cursor.getColumnIndexOrThrow("age"))}岁 · " +
                                    "${cursor.getString(cursor.getColumnIndexOrThrow("education"))}",
                            interests = cursor.getString(cursor.getColumnIndexOrThrow("interests")) ?: "",
                            avatar = cursor.getString(cursor.getColumnIndexOrThrow("avatar")),
                            matchRate = "搜索结果"
                        )
                    )
                }
            }

            recommendAdapter.submitList(users)
            dialog.dismiss()

            if (users.isEmpty()) {
                Toast.makeText(context, "未找到相关用户", Toast.LENGTH_SHORT).show()
            }
        }

        dialog.show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 